<?


class gxlib {
	var $xml; // XMLReader class
	var $innerXML; // RAW DATA
	var $ghome='gxlib/'; // Global home
	var $graph; // Main <graph> gd id
	var $default=array(
	'label'=>array('x'=>0,'y'=>0,'size'=>12,'font'=>'tahoma.ttf','color'=>'000000','angle'=>0),
	'img'=>array('x'=>0,'y'=>0,'width'=>0,'height'=>0,'type'=>'src','src'=>''),
	);
	var $logLines='';
	var $text='';
	var $lastPos=array('x'=>0,'y'=>0);

	public function log($str)
	{
		if (is_string($str))
		{
			$this->logLines.=$str."\n";
		} else {
			$this->logLines.=str_replace("  ","&nbsp;&nbsp;&nbsp;&nbsp;",var_export($str,true))."\n";
		}
	}

	// TODO
	private function CheckPath($str) {return $this->ghome.$str;}

	private function ParseIf($ifexpr)
	{
		return eval("return $ifexpr;");
	}

	private function LoadImg($src)
	{
		$ext=end(explode('.',$src));
		//die($this->CheckPath($src));
		switch (strtolower($ext))
		{

			case 'jpg':
			case 'jpeg':
				$im=imagecreatefromjpeg($this->CheckPath($src));
				break;
			case 'gif':
				$im=imagecreatefromgif($this->CheckPath($src));
				break;
			case 'png':
				$im=imagecreatefrompng($this->CheckPath($src));
				break;
		}
		return $im;
	}

	private function getAttr()
	{
		$xml=&$this->xml;
		//$node=new DOMNode();

		if ($xml->hasAttributes) {
			$r=array();
			while ($xml->moveToNextAttribute()) {
				$r[$xml->name]=$xml->value;
			}
			return $r;

		} else return false;
	}

	public function gxGraph($a)
	{
		$im=$this->LoadImg($a['src']);
		// TODO Auto size in $a var
		$g=imagecreatetruecolor($a["width"]==0?imagesx($im):$a['width'],$a["height"]==0?imagesy($im):$a["height"]);
		imagecopy($g,$im,0,0,0,0,$a["width"]==0?imagesx($im):$a['width'],$a["height"]==0?imagesy($im):$a["height"]);
		$this->graph=$g;

	}
	public function gxCGraph($a){}

	public function gxLabel($a,$text='')
	{
		if(!empty($text))
		{
			$this->text=$text;
			return $this->gxCLabel($a);
		} else return false;
	}
	private function gxCLabel($a)
	{
		// setup relative coords. TODO: In function
		if (isset($a['x'])&& is_string($a['x']) && strlen($a['x']) >= 2)
		{
			if (isset($a['x']) && $a['x'][0]=='+') $a['x']=intval($a['x'])+$this->lastPos['x'];
			elseif (isset($a['x']) && $a['x'][0]=='-') $a['x']=$this->lastPos['x']-intval($a['x']);

			if (isset($a['y']) && $a['y'][0]=='+') $a['y']=intval($a['y'])+$this->lastPos['y'];
			elseif (isset($a['y']) && $a['y'][0]=='-') $a['y']=$this->lastPos['y']-intval($a['y']);
		}
		$a+=$this->lastPos; // set over last position
		$g=&$this->graph; // Copy address
		//$this->log($a);
		$a+=$this->default['label']; // set over unset default values

		$box=imagettftext($g,$a['size'],$a['angle'],$a['x'],$a['y'],hexdec($a['color']),$this->ghome."../../fonts/".$a['font'],$this->text==''?'empty':$this->text);
		// set right label pos
		$this->lastPos['x']=$box[2];
		$this->lastPos['y']=$box[1]+($box[3]-$box[1])/2;
	}

	public function gxImg($a){}
	public function gxCImg($a){
		$a+=$this->default['img'];

		
		$src=$a['src'];
		//$this->log($src);
		switch ($a['type'])
		{
			case 'boolean':
				if ($this->ParseIf($this->text)) $src=$a['true']; else $src=$a['false'];
				break;
		}
		$im=$this->LoadImg($src);
		
		imagecopyresized($this->graph,$im,$a['x'],$a['y'],0,0, // dest pos src pos
		$a["width"]==0?imagesx($im):$a["width"], // dest w
		$a["height"]==0?imagesy($im):$a["height"], // dest h
		imagesx($im),imagesy($im)); // src w/h
		$this->lastPos['x']=$a['x']+imagesx($im);
		$this->lastPos['y']=$a['y']+imagesy($im);
	}

	public function gxSeries($a)
	{
		$this->stack=array();
		$this->lastPos['x']=$a['x'];
		$this->lastPos['y']=$a['y'];
		array_push($this->stack,$a);
	}
	public function gxcSeries($a)
	{
		$this->stack=array();
	}

	public function gxBars($a)
	{
		array_push($this->stack,$a);
	}

	public function gxLine($a)
	{
		$c=$a['color'];
		$c=imagecolorallocatealpha($this->graph,hexdec($c[0].$c[1]),hexdec($c[2].$c[3]),hexdec($c[4].$c[5]));

		imageline($this->graph,$a['x'],$a['y'],$a['x2'],$a['y2'],$c);
	}

	/**
	 * *
	 * Init
	 * @param string $xName
	 * @param bool $debug
	 * @return gxlib
	 */
	public function gxlib($xName,$debug=false)
	{
		// making links
		$xml=&$this->xml;
		$graph=&$this->graph;

		// Some stuff for security
		//if (!preg_match('#^[a-z]*$#',$xName)) return false;
		$this->ghome=$_SERVER['DOCUMENT_ROOT']."gxlib/x/$xName/";

		$xml = new XMLReader();
		$this->innerXML=file_get_contents($this->ghome.'gx.xml');
		$xml->XML($this->innerXML,'cp1251');
		$text='';
		while ($xml->read()) {
			$tag=$xml->name;
			if ($xml->nodeType == XMLReader::END_ELEMENT) $tag="C$tag";
			//echo "[$tag";
			if ($xml->hasAttributes) $a=$this->getAttr();
			//print_r($a);
			//echo "]\n";
			switch ($tag)
			{
				case '#text':
					if ($xml->hasValue && trim($xml->value)!='') {
						$this->text=$xml->value;
						//echo "[$xml->name]:" . $xml->value."<br>";

					}
					break;
				case '#comment':
					$this->log("&lt!--<b>".htmlspecialchars($xml->value)."</b>--&gt;");
					break;
				default:
					$tag="gx$tag";

					if (method_exists($this,$tag))
					{
						$this->$tag($a);
					} else {
						$this->log("<$tag> Method gxLib::$tag doesn't exists;");
						//$this->log($a);
						$this->log(htmlspecialchars($xml->readOuterXml())."<br>");
					}
			}
		}
		if ($debug)
		{
			//echo nl2br($this->logLines);
			return $graph;
		} else {

			return $graph;
		}
	}

}



